package com.example.mall.dao;

import com.example.mall.model.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class AccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void insert(Account account) {
        String sql = "insert into account (username, password, email, flag, pID) values (?, ?, ?, ?, ?)";
        jdbcTemplate.update(sql, account.getUsername(), account.getPassword(), account.getEmail(), account.getFlag(), account.getpID());
    }

    public int deleteByEmail(String email) {
        String sql = "delete from account where email = ?";
        return jdbcTemplate.update(sql, email);
    }

    public int updateUserNameByID(Account account) {
        String sql = "update account set username = ? where id = ?";
        return jdbcTemplate.update(sql, account.getUsername(), account.getId());
    }

    public int updatePasswordByEmail(Account account) {
        String sql = "update account set password = ? where id = ?";
        return jdbcTemplate.update(sql, account.getPassword(), account.getId());
    }

    public Account getById(Integer id) {
        String sql = "select * from account where id = ? lock in share mode";
        RowMapper<Account> rowMapper = new BeanPropertyRowMapper<>(Account.class);
        Account account = null;
        try {
            account = jdbcTemplate.queryForObject(sql, rowMapper, id);
        }
        catch (Exception e) {
            return account;
        }
        return account;
    }

    public Account getByMailFlag(String email, Integer flag) {
        String sql = "select * from account where email = ? and flag = ? lock in share mode";
        RowMapper<Account> rowMapper = new BeanPropertyRowMapper<>(Account.class);
        Account account = null;
        try {
            account = jdbcTemplate.queryForObject(sql, rowMapper, email, flag);
        }
        catch (Exception e) {
            return account;
        }
        return account;
    }

    public List<Account> getByMail(String email) {
        String sql = "select * from account where email = ? lock in share mode";
        RowMapper<Account> rowMapper = new BeanPropertyRowMapper<>(Account.class);
        List<Account> accountList = null;
        try {
            accountList = jdbcTemplate.query(sql, rowMapper, email);
        }
        catch (Exception e) {
            return accountList;
        }
        return accountList;
    }

}
